{include file="common/header" /}

<!-- 中间区域 -->
<script src="/public/static/xm-select.js" type="text/javascript"></script>
<main>

    <section>

        <div class="layui-main">

            <form class="order-select-form layui-form" onsubmit="return false">

                <ul class="layui-row layui-col-space24 ul_height ">

                    <li class="layui-col-md6 layui-col-xs12">

                        <div class="item"><span>产品类别:</span>

                            <div class="block">

                                <select name="goods_cate_1" lay-filter="category_select">

                                        <option value="">请选择产品类型 </option>

                                    {volist name="goods_cate" id="cat"} 

                                         <option  value="{$cat.id}"  {if isset($goods_cate_1) && $goods_cate_1 == $cat.id} selected {/if} >{$cat.title}</option>

                                    {/volist}

                                   

                                </select>

                            </div>

                        </div>

                    </li>

                    <li class="layui-col-md6 layui-col-xs12">
                            
                    </li>
                   
                    <li class="layui-col-md6 layui-col-xs12">

                        <div class="item"><span>产品分类:</span>

                            <div class="block">

                                <select name="goods_cate_2" id="goods_cate_2" lay-filter="category_select_2">
                                    <option value="">请选择产品分类</option>
                                    {if isset($goods_cate_2_list) && count($goods_cate_2_list)} 

                                        {volist name="goods_cate_2_list" id="cate"} 

                                            <option value="{$cate.id}" {if isset($goods_cate_2) && $goods_cate_2 == $cate.id } selected {/if}>{$cate.title}</option>

                                        {/volist}
                                    {/if}
                                    
                                </select>

                            </div>

                        </div>

                    </li>
                    <li class="layui-col-md6 layui-col-xs12">

                        <div class="item"><span>产品分类:</span>

                            <div class="block">

                                <select name="goods_cate_3" id="goods_cate_3" lay-filter="category_select_3">
                                    <option value="">请选择产品分类</option>
                                    {if isset($goods_cate_3_list) && count($goods_cate_3_list)} 

                                        {volist name="goods_cate_3_list" id="cate"} 

                                            <option value="{$cate.id}" {if isset($goods_cate_3) && $goods_cate_3 == $cate.id } selected {/if}>{$cate.title}</option>

                                        {/volist}
                                    {/if}
                                </select>

                            </div>

                        </div>

                    </li>
                
                    {if isset($spec_list)}
                    {volist name="spec_list" id="spec"} 

                        {if $spec.type == 'input'} 

                            <li class="layui-col-md4 layui-col-xs12 apecs_item">

                                <div class="item"><span>{$spec.name}:</span>

                                    <div class="block">

                                        <input type="text" class="layui-input" name="{$spec.id}" placeholder="请输入{$spec.name}" value="{$product_select[$spec.id]|default=''}">

                                    </div>

                                </div>

                            </li>

                        {/if}

                        {if $spec.type == 'select'} 

                            <li class="layui-col-md4 layui-col-xs12 apecs_item">

                                <div class="item"><span>{$spec.name}:</span>

                                    <div class="block">

                                        <select name="{$spec.id}">

                                            {if count($spec.values)} 

                                                    <option value="">请选择{$spec.name}</option>

                                                {volist name="spec.values" id="values"} 

                                                    <option value="{$values.id}" {if isset($product_select[$spec.id]) && $product_select[$spec.id] == $values.id } selected {/if}>{$values.value}</option>

                                                {/volist} 

                                            {/if}

                                    

                                        </select>

                                    </div>

                                </div>

                            </li>

                        {/if}

                        {if $spec.type == 'checkbox'}
                            
                            <li class="layui-col-md4 layui-col-xs12 apecs_item">
                                <div class="item">
                                    <span>{$spec.name}:</span>
                                    <div class="block" id="checkbox{$spec.id}">
                                      
                                    </div>
                                    <script>
                                        // 动态生成 xmSelect 的数据
                                        var data = [
                                          // 遍历规格值，生成选项
                                          {volist name="spec.values" id="values"}
                                          {
                                            name: '{$values.value}', // 显示的名称
                                            value: '{$values.id}',  // 对应的值
                                            selected: {if isset($product_select[$spec.id]) && in_array($values.id, explode(',', $product_select[$spec.id]))} true {else} false {/if}, // 是否默认选中
                                          },
                                          {/volist}
                                        ];
                                    
                                        // 初始化 xmSelect
                                        xmSelect.render({
                                          el: '#checkbox{$spec.id}', // 绑定容器
                                          name: '{$spec.id}',
                                          data: data, // 动态生成的数据
                                          toolbar: {
                                                show: true, // 隐藏工具栏（包括全选按钮）
                                            },
                                          filterable: true,
                                           theme: {
                                            color: '#404D5A', // 主题颜色
                                          },
                                        });
                                      </script>
                                </div>
                            </li>
                        {/if}

                    {/volist}

                    {/if}

                </ul>



                <div class="flex-center mt40 gap30 gap10-xs">

                    <a href="/site-List-5" type="reset" class="layui-btn">重置选项</a>

                    <button class="layui-btn" lay-submit lay-filter="search_goods">立即查询</button>

                </div>

            </form>



            <div class="mt26 select_list_total">

                <div class="d-flex al-c gap20 layui-form">

                    <span>排序</span>

                    <select>

                        <option>默认</option>

                    </select>

                </div>

                <span class="ft20">搜索到{$goods_model_count|default=0}条</span>

                <div class="pagenum2">

                    <div id="demo-laypage-normal-2"></div>

                </div>

            </div>





            <ul class="select-product mt30">

                {if isset($goods_models) &&  count($goods_models)} 

                    {volist name="goods_models" id="models"} 

                        <li data-modelid="{$models.id}" data-goodsid="{$models.goods_id}">

                            <div>

                                <i class="check-img"></i>

                            </div>

                            <div class="info">

                                <div class="img_100">

                                    <img src="{$models.thumb}">

                                </div>

                                <div style="text-align: center;">{$models.goods ? $models.goods.title :''}</div>

                                <div style="text-align: center;">{$models.name}</div>

                                <div class="num-box" data-type="number">

                                <i lay-on="sub" class="layui-icon layui-icon-subtraction"></i>

                            <input data-name="number" class="layui-input cart_num"  value="1">

                                <i lay-on="add" class="layui-icon layui-icon-addition"></i>

                            </div>

                            <a class="layui-btn layui-btn-primy add_cart" data-modelid="{$models.id}" data-goodsid="{$models.goods_id}">加入购物车</a>

                            <a href="/goods-detail-{$models.goods_id}" class="layui-btn layui-btn-primy">查看详情</a>

                            </div>

                            <dl>

                                {if count($models.attributes_info)} 

                                    {volist name="$models.attributes_info" id="attribute"} 

                                        <dd>

                                            <p>{$attribute.name}：</p>

                                            <p>{$attribute.value}</p>

                                        </dd>

                                    {/volist}

                                {/if}

                            </dl>

                        </li>

                    {/volist}

                {/if}

                    

            </ul>



            <div class="pagenum1">



                <div id="demo-laypage-normal-1"></div>

            </div>

        </div>

    </section>

</main>

<div class="order-confrim">

    <div class="layui-main d-flex al-c jc-s">

        <div>购物车已选择<span data-count="all"> 0</span> 件产品</div>

        <button class="layui-btn red-btn sure_order">立即下单</button>

    </div>

</div>

<script src="__ROOT__/public/home/js/index.js"></script>

<script src="__ROOT__/public/static/index.js"></script>



<script>

    layui.use(function () {

        var laypage = layui.laypage;

        // 普通用法

        laypage.render({

            elem: 'demo-laypage-normal-1',

            count: 50, 

            limit: 6,

            curr : {$goods_model_page|default=0},

            count: {$goods_model_count|default=0},

            jump: function(obj, first){

                // obj 包含了当前分页的所有参数

                let page = obj.curr;



                // 获取当前 URL 和查询参数

                let url = new URL(location.href);

                let params = new URLSearchParams(url.search);



                // 设置或更新 page 参数

                params.set('page', page);



                // 将更新后的参数应用到 URL

                url.search = params.toString();



                // 首次不执行

                if (!first) {

                     // 跳转到新的 URL

                    location.href = url.toString();

                }

            }

        });



        laypage.render({

            elem: 'demo-laypage-normal-2',

            count: 10,

            first: '首页',

            last: '尾页',

            prev: false,

            next: false,

            limit: 10,

            curr : {$goods_model_page|default=0},

            count: {$goods_model_count|default=0},

            jump: function(obj, first){

                // obj 包含了当前分页的所有参数

                let page = obj.curr;



                // 获取当前 URL 和查询参数

                let url = new URL(location.href);

                let params = new URLSearchParams(url.search);



                // 设置或更新 page 参数

                params.set('page', page);



                // 将更新后的参数应用到 URL

                url.search = params.toString();



                // 首次不执行

                if (!first) {

                     // 跳转到新的 URL

                    location.href = url.toString();

                }

            }

        });

    });



  



</script>



<script>

    $(document).on('click', '.select-box dd', function () {

        $(this).toggleClass('active');

        var arr = [];

        $(this).closest('dl').find('.active').each(function () {

            arr.push($(this).find('span').text())

        })

        console.log(arr)

        $(this).closest('.select-auto-box').children('input').val(arr.join('、'))

    })

    

    $(document).on('click', '.check-img', function () {

        $(this).closest('li').toggleClass('active')

        $('[data-count="all"]').text($('.select-product li.active').length)

    })

    layui.use('form', function(){

        var form = layui.form;

        form.on('select(category_select)', function (data) {
            var categoryId = data.value;
            if (!categoryId) return;
           $('.apecs_item').remove();
            // 请求二级分类数据
            ajaxRequest('/get-second-category', { parent_id: categoryId }, 'POST', this, function (response) {
                var secondSelect = document.querySelector('select[name="goods_cate_2"]');
                secondSelect.innerHTML = '<option value="">请选择产品分类</option>';
                if(response.data.length){
                    response.data.forEach(function (item) {
                        secondSelect.innerHTML += `<option value="${item.id}">${item.title}</option>`;
                    });
                    form.render('select');
                }
                
            });
        });
         // 监听二级分类选择
        form.on('select(category_select_2)', function (data) {
            var categoryId = data.value;
            if (!categoryId) return;
            $('.apecs_item').remove();
            // 请求三级分类数据
            ajaxRequest('/get-second-category', { parent_id: categoryId }, 'POST', this, function (response) {
                var thirdSelect = document.querySelector('select[name="goods_cate_3"]');
                thirdSelect.innerHTML = '<option value="">请选择产品分类</option>';
                response.data.forEach(function (item) {
                    thirdSelect.innerHTML += `<option value="${item.id}">${item.title}</option>`;
                });
                form.render('select');
            });
        });
        form.on('select(category_select_3)', function(data){
            var thirdCategoryId = data.value;
            let url = data.value
            var firstCategoryId = document.querySelector('select[name="goods_cate_1"]').value;
            var secondCategoryId = document.querySelector('select[name="goods_cate_2"]').value;
            if (url) {
                window.location.href = "/site-List-5.html?goods_cate_1=" + firstCategoryId + "&goods_cate_2=" + secondCategoryId + "&goods_cate_3=" + thirdCategoryId;

            }

         }); 

        //监听提交

        form.on('submit(search_goods)', function(data){

            var formData = data.field;

            formData.spec = 1;

            // 将表单数据转换为URL参数字符串，过滤掉空值

            var queryString = Object.keys(formData)

                .filter(function(key) {

                    // 过滤掉空值（包括空字符串、null、undefined）

                    return formData[key] !== '' && formData[key] != null;

                })

                .map(function(key) {

                    // 对键和值进行编码

                    return encodeURIComponent(key) + '=' + encodeURIComponent(formData[key]);

                })

                .join('&');



            // 获取当前页面的URL（不包含参数）

            var currentUrl = window.location.href.split('?')[0];



            // 如果有参数，附加到当前URL上

            var newUrl = currentUrl + (queryString ? '?' + queryString : '');



            // 跳转到新的URL（发起GET请求）

            window.location.href = newUrl;



            return false; // 阻止表单默认提交

        });

    });



    $(document).on('click', '.search_goods', function() {

        // 创建一个对象来存储用户选择的数据

        var formData = {};

        

        // 获取表单中所有的输入项

        $('form.order-select-form').find('select, input').each(function() {

            var name = $(this).attr('name'); // 获取属性名称

            var value = $(this).val(); // 获取属性值

            

            if (value) {  // 如果有选择值

                formData[name] = value;

            }

        });



        // 提交表单数据

        $.ajax({

            url: '/search-products', // 后端处理搜索的接口

            type: 'POST',

            data: formData,

            success: function(response) {

                if (response.code === 1) {

                    // 成功后，渲染产品列表

                    renderProducts(response.data);

                } else {

                    layer.msg(response.msg || '搜索失败', { icon: 2 });

                }

            }

        });

    });



    $(document).on('click', '.add_cart', function () {

        let goods_id = $(this).data('goodsid');

        let model_id = $(this).data('modelid');



        let cart_num = $(this).closest('.info').find('.cart_num').val(); // 修正这里的查找方式



        let field = {

            goods_id: goods_id,

            model_id: model_id,

            cart_num: cart_num

        };







        ajaxRequest('/goods-cart-add', field, 'POST', this, function (response) {

            layer.msg('添加成功', {icon: 1, time: 2000}, function () {});

        });

    });





    $(document).on('click', '.sure_order', function () {

        let selectedItems = [];



        // 筛选所有已选中的商品（带 .active 类的 li）

        $('li.active').each(function () {

            let goods_id = $(this).data('goodsid'); // 获取商品ID

            let model_id = $(this).data('modelid'); // 获取型号ID

            let cart_num = $(this).find('.cart_num').val(); // 获取数量



            if (goods_id && model_id && cart_num > 0) {

                selectedItems.push({

                    goods_id: goods_id,

                    model_id: model_id,

                    cart_num: cart_num

                });

            }

        });



        if (selectedItems.length === 0) {

            layer.msg('请选择商品后再下单', { icon: 2 });

            return;

        }



        // 发送 AJAX 请求

        ajaxRequest('/submit-order-batch', { items: selectedItems }, 'POST', this, function (response) {

            layer.msg('下单成功', { icon: 1, time: 2000 }, function () {

                window.location.href = '/index/member/';

            });

        });

    });



    

</script>

<!-- 中间区域结束 -->

{include file="common/footer" /}